package com.ojoin.trade.supplyloan_core.web.controller;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jms.Destination;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Maps;
import com.ojoin.trade.bpm.web.service.BpmTaskService;
import com.ojoin.trade.bpm.web.support.ProcessMessageVO;
import com.ojoin.trade.common.Constants;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.TimeUtils;
import com.ojoin.trade.common.web.controller.SimpleBaseController;
import com.ojoin.trade.common.web.domain.Result;
import com.ojoin.trade.common.web.service.IRSAService;
import com.ojoin.trade.common_core.utils.TradeUtils;
import com.ojoin.trade.supplyloan_core.web.domain.Order;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlLoanCreditLog;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlProcessInfoVO;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlStatusCreditLogVo;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlSupplyInventory;
import com.ojoin.trade.supplyloan_core.web.service.QueueSenderServie;
import com.ojoin.trade.supplyloan_core.web.service.TbSlLoanApplicationService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlLoanCreditService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlLoanService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlProcessInfoService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlSupplyInventoryService;

@Controller
@RequestMapping("/operate/slcredit")
public class SlCreditLogBpmController  extends SimpleBaseController {

    private Logger log = LoggerFactory.getLogger(SlCreditLogBpmController.class);

    @Autowired
    private TbSlLoanService loanService;
    
    @Autowired
	private BpmTaskService bpmTaskService;
    @Autowired
    private TbSlLoanCreditService creditService;
    @Autowired
    private TbSlLoanApplicationService tbSlLoanApplicationService;

    @Autowired
    private TbSlProcessInfoService tbSlProcessInfoService;

    @Autowired
    private IRSAService rsaSrv;

    @Autowired
    private QueueSenderServie queueSenderServie;

    @Autowired
    private TbSlSupplyInventoryService inventoryService;
    
    @Autowired
    @Qualifier("creditLogQueueDestination")
    private Destination destination;
    
    @Autowired
	@Qualifier("catchDataTask")
	private Destination catchDataTask;

    @ResponseBody
    @RequestMapping(value = "/slfirsttrialCommit",method = RequestMethod.POST)
    public Result  slfirsttrialCommit(HttpServletRequest request,String processinfoid,String joinuserid,String rowUpdateTime,String loan_voucher,String paymentNotice,String contract,String loanregist,String taskid,String processid,String memo, Integer[] inventoryids, String loan_code){
        int idOfTbFactoryingCompany=TradeUtils.getOperatorCompany(request);
        if(StringUtils.isEmpty(processinfoid)){
            return new Result(Result.Status.ERROR,"未选择任何需要初审的贷款数据");
        }
        if(StringUtils.isEmpty(rowUpdateTime)){
            return  new Result(Result.Status.ERROR,"贷款的时间戳不可为空");
        }
        if(StringUtils.isEmpty(joinuserid)){
            return new Result(Result.Status.ERROR,"joinid不能为空");
        }
        if(StringUtils.isEmpty(loan_voucher)){
            return new Result(Result.Status.ERROR,"凭证不能为空");
        }
//        if(StringUtils.isEmpty(contract)){
//            return new Result(Result.Status.ERROR,"合同详情不能为空");
//        }
        if(StringUtils.isEmpty(loanregist)){
            return new Result(Result.Status.ERROR,"不动资产登记不能为空");
        }
        
        if(joinuserid.equals("123") && (inventoryids == null || inventoryids.length == 0)) {
        	return new Result(Result.Status.ERROR,"天津方鑫商户放款时，对应收货订单不可为空");
        }
        
        if(joinuserid.equals("123") && (StringUtils.isEmpty(loan_code))) {
        	return new Result(Result.Status.ERROR,"天津方鑫商户放款时，对应融资编号不可为空");
        }
        
        int join=Integer.parseInt(joinuserid);
        Date timedate=new Date(CommonUtils.getLong(rowUpdateTime));
        rowUpdateTime=TimeUtils.getDateString(timedate);
          try{
        	  
              loanService.updateForfirsttrialSuccess(Integer.parseInt(processinfoid), idOfTbFactoryingCompany, rowUpdateTime,loan_voucher,paymentNotice,join,contract,loanregist);
             
              //天津方鑫商户需要更新该笔融资对应入库单状态及融资编号
              if (CommonUtils.getInt(joinuserid) == 123 && inventoryids != null && inventoryids.length > 0 && !StringUtils.isEmpty(loan_code)) {
	              List<TbSlSupplyInventory> list = new ArrayList<TbSlSupplyInventory>();
	              for(Integer id : inventoryids) {
	              	TbSlSupplyInventory vo = new TbSlSupplyInventory();
	              	vo.setId(id);
	              	vo.setItemStatus(TbSlSupplyInventory.PAY);
	              	vo.setLoanCode(loan_code);
	              	list.add(vo);
	              }
	              
		          	inventoryService.updateJDBCBatch(list);
		          	
		          	// 重新统计可提款额
		          	Order order = new Order(Order.STATTOTAL);
		      		order.getParames().put("platformUserId", "101");
		      		
		      		queueSenderServie.send(catchDataTask, order);
              	}
              try{
                  memo= URLDecoder.decode(memo, Constants.ENCODING);
              }catch(Exception e){

              }
              Map<String,Object> taskVars=new HashMap();
              taskVars.put("pass", "1");
              bpmTaskService.complete(taskid, processid, memo, taskVars);
              return new Result(Result.Status.OK,"初审成功");

          }catch (Exception e){
              log.error("贷款初审失败",e);
              if(e instanceof BusinessException){
               return new Result(Result.Status.ERROR,e.getMessage());
              }
              return new Result(Result.Status.ERROR,"初审失败");
          }
    }
    @ResponseBody
    @RequestMapping(value="/confirm",method = RequestMethod.POST)
    public Result confirm(HttpServletRequest request,String taskid,String processid){
        try{
            Map<String,Object> taskVars=new HashMap();
            taskVars.put("pass", "1");
            bpmTaskService.complete(taskid, processid,"确认成功", taskVars);
            return new Result(Result.Status.OK,"确认成功");
        }catch (Exception e){
            if(e instanceof BusinessException){
                return new Result(Result.Status.ERROR,e.getMessage());
            }
            return new Result(Result.Status.ERROR,"确认失败");
        }



    }
    @ResponseBody
    @RequestMapping(value="/pass",method = RequestMethod.POST)
    public Result pass(HttpServletRequest request,String taskid,String processid,String memo){
        try{
            Map<String,Object> taskVars=new HashMap();
            try{
                memo= URLDecoder.decode(memo, Constants.ENCODING);
            }catch(Exception e){

            }
            taskVars.put("pass", "1");
            bpmTaskService.complete(taskid, processid,memo, taskVars);
            return new Result(Result.Status.OK,"审核通过");
        }catch (Exception e){
            if(e instanceof BusinessException){
                return new Result(Result.Status.ERROR,e.getMessage());
            }
            return new Result(Result.Status.ERROR,"通过失败");
        }

    }

    @ResponseBody
    @RequestMapping(value="/reject",method =RequestMethod.POST )
    public Result reject(HttpServletRequest request,String taskid,String processid,String memo,Integer processinfoid){
        try{
            Map<String,Object> taskVars=new HashMap();
            taskVars.put("pass", "0");
            try{
                memo= URLDecoder.decode(memo, Constants.ENCODING);
            }catch(Exception e){

            }
            if(StringUtils.isEmpty(memo)){
                return new Result(Result.Status.ERROR,"驳回理由不能为空");
            }

            loanService.updateForRejectCredit(processinfoid);
            bpmTaskService.complete(taskid, processid, "驳回原因：" + memo, taskVars);
            return new Result(Result.Status.OK,"驳回成功");
        }catch (Exception e){
            if(e instanceof BusinessException){
                return new Result(Result.Status.ERROR,e.getMessage());
            }
            return new Result(Result.Status.ERROR,"驳回失败");
        }
    }
    @ResponseBody
    @RequestMapping(value = "/refuse",method = RequestMethod.POST)
    public Result refuse(HttpServletRequest request,String taskid,String processid,String processInfoId,String memo,String rowUpdateTime){
        if(StringUtils.isEmpty(processInfoId)){
            return new Result(Result.Status.ERROR,"未选择任何需要拒绝的贷款数据");
        }

        try{
            memo= URLDecoder.decode(memo, Constants.ENCODING);
        }catch(Exception e){

        }
        if(StringUtils.isEmpty(memo)){
            return new Result(Result.Status.ERROR,"拒绝理由不能为空");
        }
        try{
            loanService.updateForRefuseCredit(Integer.parseInt(processInfoId),"拒绝理由："+memo, rowUpdateTime);
            Map<String,Object> taskVars=new HashMap();
            taskVars.put("pass", "0");
            bpmTaskService.complete(taskid, processid,"拒绝理由："+memo, taskVars);
            return new Result(Result.Status.OK,"拒绝放款成功");
        }catch (Exception e){
        	LogUtils.error(log, e);
            if(e instanceof BusinessException){
                return new Result(Result.Status.ERROR,e.getMessage());
            }
            return new Result(Result.Status.ERROR,"拒绝放款有误");
        }


    }
     @ResponseBody
     @RequestMapping(value = "/slrealloan",method = RequestMethod.POST)
     public Result realloan(HttpServletRequest request,String processinfoid,String  rowUpdateTime,String pwd,String idofLoanInfo,String tsOfLoanInfo,String voucher,String taskid,String processid)
     {
         if(StringUtils.isEmpty(processinfoid)){
             return new Result(Result.Status.ERROR,"未选择任何的贷款记录");
         }
         if(StringUtils.isEmpty(rowUpdateTime)){
             return new Result(Result.Status.ERROR,"上一次变更的时间为空");
         }
         if(CommonUtils.isEmpty(voucher)&&StringUtils.isEmpty(pwd)){
             return  new Result(Result.Status.ERROR,"支付密码不能为空");
         }

         Integer idOfTbFactoryingOperator=CommonUtils.getLoginUserId();
         String mhtnofrom=TradeUtils.getOperatorCompanyMhtNo();

         pwd=rsaSrv.decryptStringByJs(pwd);
         Integer idofloaninfo=null;
         if(!CommonUtils.isEmpty(idofLoanInfo)){
             idofloaninfo=CommonUtils.getInteger(idofLoanInfo);
         }
         Date timedate=new Date(CommonUtils.getLong(rowUpdateTime));
         rowUpdateTime=TimeUtils.getDateString(timedate);
         if(!CommonUtils.isEmpty(tsOfLoanInfo)){
             Date timedate1=new Date(CommonUtils.getLong(tsOfLoanInfo));
             tsOfLoanInfo=TimeUtils.getDateString(timedate1);
         }
         try{
             loanService.updateForRealLoan(Integer.parseInt(processinfoid), idOfTbFactoryingOperator, mhtnofrom, pwd,idofloaninfo,rowUpdateTime,tsOfLoanInfo,voucher,taskid,processid);


             return new Result(Result.Status.OK,"放款成功");
         }catch (Exception e){
             log.error("放款失败",e);
             if(e instanceof BusinessException){
                 return new Result(Result.Status.ERROR,e.getMessage());
             }
             return new Result(Result.Status.ERROR,"放款失败");
         }
     }



    @ResponseBody
    @RequestMapping(value = "/audit",method = RequestMethod.GET)
	public Result audit(HttpServletRequest request, TbSlLoanCreditLog slLoan) {
		String taskDefKey = slLoan.getBpm().getTaskDefKey();
		// 提交流程任务
		Map<String, Object> vars = Maps.newHashMap();
		bpmTaskService.complete(slLoan.getBpm().getTaskId(), slLoan.getBpm().getProcInsId(), "统统通过", vars);

		return new Result(Result.Status.ERROR, "审核完成");
	}
    @ResponseBody
    @RequestMapping(value="initProcess",method = RequestMethod.GET)
    public Result initProcess(HttpServletRequest request,Integer id){
        if(CommonUtils.isEmpty(id)){
            return new Result(Result.Status.ERROR,"贷款不能为空");
        }
        try{
         List<TbSlStatusCreditLogVo> logList=creditService.queryCreditByProcessid(id);
        if(CommonUtils.isEmpty(logList)){
            return new Result(Result.Status.ERROR,"数据有问题");
        }
        Map<String,Object> vars=tbSlLoanApplicationService.initProcessRole(logList.get(0).getId());
        StringBuilder title=new StringBuilder();
        for(TbSlStatusCreditLogVo vo:logList){
            title.append(vo.getCode()).append(" ");
        }

            String loginName = CommonUtils.getPrincipal().getLoginName();
            ProcessMessageVO vo = new ProcessMessageVO();
            vo.setProcDefKey("SLCredit");
            vo.setBusinessTable("tb_sl_loan_credit_log");
            vo.setBusinessId(String.valueOf(id));
            vo.setLoginName(loginName);
            vo.setTitle(title.toString());
            vo.setVars(vars);
            queueSenderServie.send(destination, vo);
            return new Result(Result.Status.OK,"启动流程成功");
            }catch (Exception e){
            return new Result(Result.Status.ERROR,"启动流程失败");
        }

    }
    
	@RequestMapping(value = "newform")
	public String newform(TbSlLoanCreditLog slLoan) {
        int id=slLoan.getId();
       // TbSlLoanCreditLog logvo= creditService.queryCreditLogById(slLoan.getId());
        TbSlStatusCreditLogVo  logvo= creditService.queryStatusCreditLogVo(slLoan.getId());
        long time= logvo.getRowUpdateTime().getTime();

        String taskDefKey = slLoan.getBpm().getTaskDefKey();
        String status = slLoan.getBpm().getStatus();


        String view = "/operate/paltformdetail.html?joinid="+logvo.getUserIdOfJoinOfDebtor()+"&rowUpdateTime="+time+"&id="+slLoan.getId()+"&fileowner="+logvo.getUserIdOfJoinOfDebtor()+"&taskid="+slLoan.getBpm().getTaskId()+"&processid="+slLoan.getBpm().getProcInsId()+"&creditstatus="+logvo.getCreditstatus()+"&fileinput="+logvo.getLoanVoucher()+"&uploadcontract="+logvo.getContract()+"&uploadloanregist="+logvo.getLoanregist()+"&taskDefKey="+taskDefKey+"&status="+status;
		// 查看审批申请单
		if (null!=slLoan.getBpm().getProcInsId()){
			//自定义任务环节编号
            if(taskDefKey.equals("makeLoan")){
                Long loantime=null;
                if(!CommonUtils.isEmpty(logvo.getTsOfLoanInfo()))
                { loantime=logvo.getTsOfLoanInfo().getTime();}
                Integer idofbank=logvo.getIdOfBankAcc();
                String idofbankstr="";
                if(!CommonUtils.isEmpty(idofbank)){
                    idofbankstr=idofbank.toString();
                }
                view= "/operate/paltformreview.html?joinid="+logvo.getUserIdOfJoinOfDebtor()+"&taskid="+slLoan.getBpm().getTaskId()+"&processid="+slLoan.getBpm().getProcInsId()+"&id="+slLoan.getId()+"&idOfBankAcc="+idofbankstr+"&rowUpdateTime="+time+"&idofLoanInfo="+logvo.getIdofLoanInfo()+"&tsOfLoanInfo="+loantime+"&creditstatus="+logvo.getCreditstatus()+"&taskDefKey="+taskDefKey+"&status="+status;
            }
		}
      return "redirect:"+ view;
	}
    @RequestMapping(value = "form")
    public String Form(TbSlProcessInfoVO processInfoVO) {
        int id=processInfoVO.getId();
       TbSlProcessInfoVO vo=tbSlProcessInfoService.queryLoanInfoVoByProcess(id);
        long time= vo.getRowUpdateTime().getTime();

        String taskDefKey = processInfoVO.getBpm().getTaskDefKey();
        String status = processInfoVO.getBpm().getStatus();

        String view = "/operate/paltformdetail.html?id="+id+"&rowUpdateTime="+time+"&taskid="+processInfoVO.getBpm().getTaskId()+"&processid="+processInfoVO.getBpm().getProcInsId()+"&creditstatus="+vo.getLoanStatus()+"&joinid="+vo.getUserIdOfJoinOfDebtor()+"&taskDefKey="+taskDefKey+"&status="+status;
        // 查看审批申请单
        if (null!=processInfoVO.getBpm().getProcInsId()){
            //自定义任务环节编号
            if(taskDefKey.equals("makeLoan")){
                Long loantime=null;
                if(!CommonUtils.isEmpty(vo.getTsOfLoanInfo()))
                { loantime=vo.getTsOfLoanInfo().getTime();}

                view= "/operate/paltformreview.html?id="+id+"&taskid="+processInfoVO.getBpm().getTaskId()+"&processid="+processInfoVO.getBpm().getProcInsId()+"&creditstatus="+vo.getLoanStatus()+"&idofLoanInfo="+vo.getIdOfLoanInfo()+"&tsOfLoanInfo="+loantime+"&rowUpdateTime="+time+"&joinid="+vo.getUserIdOfJoinOfDebtor()+"&taskDefKey="+taskDefKey+"&status="+status;
            }
        }
        return "redirect:"+ view;
    }
}

